import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes } from '@/router'
import { login, getUserInfo } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {},
  router: constantRoutes
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  getUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 退出登录删除token用的后面写
  removeToken(state) {
    state.token = null
    removeToken()
    resetRouter()
  },
  // 添加动态路由
  setRouter(state, newRouter) {
    console.log(newRouter)
    state.router = [...constantRoutes, ...newRouter]
  }
}

const actions = {
  async login(context, data) {
    // console.log(data)
    // 利用传过来的用户名和密码获取token
    const res = await login(data)
    // 调mutations把token存到state中
    context.commit('setToken', res)
  },
  async getUserInfo(context) {
    // 调获取用户信息的接口
    const res = await getUserInfo()
    // 调mutations中的方法把获取到的用户信息存到state中
    context.commit('getUserInfo', res)
    return res
  },
  logout(context) {
    // 删除token
    context.commit('removeToken')
    // 清空用户信息
    context.commit('getUserInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
